<template>
	<div class="main">
		<!-- 搜索框和导航栏容器 -->
		<div class="fixed-header">
		<!-- <div class=""> -->
			<!-- 搜索框 -->
			<div class="search-box">
				<u-search placeholder="请输入商品名称" v-model="searchText" :show-action="true" @change="onSearchChange"
					@search="onSearch" @custom="onSearch" @focus="onSearchFocus" @blur="onSearchBlur"
					:disabled="isSearching" />
			</div>
			<!-- 搜索历史 -->
			<div class="search-history" v-if="isSearchFocused && !hasSearched">
				<div class="history-header">
					<div class="history-title">搜索历史</div>
					<u-icon name="trash" size="16" @click="clearHistory"></u-icon>
				</div>
				<div class="history-tags">
					<text class="history-tag" v-for="item in searchHistory" :key="item"
						@click="selectSuggestion(item)">{{ item
          }}</text>
				</div>
			</div>

		</div>
		<!-- 内容区域 -->
		<div class="content-container">
			<!-- 排序选择栏 -->
			<div class="sort-bar" v-if="searchGoods.length > 0" :class="{ 'sort-bar-fixed': isSticky }">
				<div class="sort-item" @click="sortByComprehensive">
					<text :class="{ active: sortType === 'comprehensive' }">综合</text>
				</div>
				<div class="sort-item" @click="sortByPrice">
					<text :class="{ active: sortType === 'price' }">价格</text>
					<text class="sort-arrow">{{ sortOrder === 'asc' ? '↑' : '↓' }}</text>
				</div>
				<div class="sort-item" @click="toggleViewMode">
					<u-icon :name="viewMode === 'grid' ? 'list' : 'grid'" size="20"></u-icon>
				</div>
			</div>
			<!-- 商品列表 -->
			<div class="search-loading" v-if="isSearching">
				<u-loading-icon mode="circle" size="28"></u-loading-icon>
				<text>搜索中...</text>
			</div>
			<div class="goods-container" v-else>
				<div :class="['goods-list', { 'list-view': viewMode === 'list' }]">
					<div v-for="(item, index) in searchGoods" :key="index" class="goods-item"
						@click="dispatchOrder(item)">
						<div class="goods-image">
							<img :src="item.pictureUrl" alt="商品图片">
							<div class="goods-tag" v-if="item.tag">{{ item.tag }}</div>
						</div>
						<div class="goods-info">
							<p class="goods-title">{{ item.commodityName }}</p>
							<div class="goods-price-row">
								<p class="goods-price">￥{{ item.price }}</p>
								<p class="goods-unit">/{{ item.unitName }}</p>
							</div>
						</div>
					</div>
				</div>
			</div>
			<loading-footer :status="status" :slot-empty="true">
				<view slot="empty" class="column-center" style="padding-top: 200rpx">
					<image class="img-null" src="/static/images/goods_null.png"></image>
					<text style="color: #666666;">暂无商品</text>
				</view>
			</loading-footer>
			<!-- 返回顶部按钮 -->
			<u-back-top :scroll-top="scrollTop" :top="875" :right="20" @click="backToTop"></u-back-top>
		</div>
	</div>
</template>

<script>
	import {
		getGoodsInfo,
		searchGoods
	} from '@/api/goods/goods.js'
	export default {
		data() {
			return {
				searchText: '',
				sortType: 'comprehensive',
				sortOrder: 'desc',
				viewMode: 'list',
				categories: [],
				allGoods: [],
				scrollTop: 0,
				searchGoods: [],
				hasSearched: false,
				searchHistory: [],
				status: 'empty',
				isSearchFocused: false,
				isSticky: false,
				isSearching: false,
			};
		},
		onPageScroll(e) {
			// 更新滚动位置
			this.scrollTop = e.scrollTop;
			// 当滚动超过一定距离时，使排序栏吸顶
			this.isSticky = e.scrollTop >= 50; // 调整为更合适的吸顶触发距离
		},
		onLoad() {
			this.getGoodsTypeInfo();
			this.loadSearchHistory();
		},
		methods: {
			getGoodsTypeInfo() {
				getGoodsInfo().then(res => {
					console.log(res);

					this.searchGoods = res.goodsInfo[2]
					this.searchGoods = this.searchGoods.map(v => {
						return {
							...v,
							count: 1
						}
					})
					this.status = 'success'
				})
			},
			dispatchOrder(item) {
				// 跳转到新页面，并传递选中的商品信息
				uni.navigateTo({
					url: `/pages/goods/dispatch?selectedGood=${JSON.stringify(item)}`
				});
			},
			onSearchChange(value) {
				this.hasSearched = false;
			},
			onSearch() {
				if (!this.searchText.trim()) return;
				this.isSearching = true;
				this.hasSearched = true;
				this.addToHistory(this.searchText);
				// 模拟搜索延迟
				setTimeout(() => {
					searchGoods({
						keyword: this.searchText
					}).then(res => {
						this.searchGoods = res.map(item => ({
							...item,
							count: 1 // 为每个商品添加count属性并初始化为0
						}));
						this.status = this.searchGoods.length > 0 ? 'success' : 'empty';
					}).finally(() => {
						this.isSearching = false;
					});
				}, 500);
			},
			selectSuggestion(text) {
				this.searchText = text;
				this.onSearch();
				this.isSearchFocused = false;
			},
			loadSearchHistory() {
				const history = uni.getStorageSync('searchHistory');
				this.searchHistory = history ? JSON.parse(history) : [];
			},
			addToHistory(keyword) {
				if (!this.searchHistory.includes(keyword)) {
					this.searchHistory.unshift(keyword);
					if (this.searchHistory.length > 10) {
						this.searchHistory.pop();
					}
					uni.setStorageSync('searchHistory', JSON.stringify(this.searchHistory));
				}
			},
			clearHistory() {
				uni.showModal({
					title: '提示',
					content: '确定要清空搜索历史吗？',
					success: (res) => {
						if (res.confirm) {
							this.searchHistory = [];
							uni.removeStorageSync('searchHistory');
						}
					}
				});
			},
			sortByComprehensive() {
				this.sortType = 'comprehensive';
			},
			sortByPrice() {
				this.sortType = 'price';
				this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
				this.searchGoods.sort((a, b) => {
					if (this.sortOrder === 'asc') {
						return a.price - b.price;
					} else {
						return b.price - a.price;
					}
				});
			},
			toggleViewMode() {
				this.viewMode = this.viewMode === 'grid' ? 'list' : 'grid';
			},
			backToTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
			},
			onSearchFocus() {
				this.isSearchFocused = true;
			},
			onSearchBlur() {
				setTimeout(() => {
					this.isSearchFocused = false;
				}, 200);
			},
		}
	}
</script>

<style lang="scss" scoped>
	.fixed-header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 100;
		background-color: #fff;
	}

	.content-container {
		padding-top: 50px; // 增加顶部间距，为固定的搜索框和导航栏留出空间
	}

	.main {
		min-height: 100vh;
		background-color: #f5f7fa;
		padding-bottom: 60px;
	}

	.search-box {
		padding: 8px 15px;
		background-color: #ffffff;
	}

	.sort-bar {
		margin: 10px 15px;
		background-color: #fff;
		border-radius: 8px;
		display: flex;
		padding: 10px 0;
		transition: all 0.3s;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05), 0 -2px 4px rgba(0, 0, 0, 0.05);
		position: relative;
		z-index: 1;

		&.sort-bar-fixed {
			position: fixed;
			top: 50px; // 调整吸顶后的位置，与搜索框保持适当距离
			left: 0;
			right: 0;
			z-index: 99;
			margin: 0;
			border-radius: 0;
			padding: 12px 0; // 吸顶时稍微增加一点内边距
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		}

		.sort-item {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 14px;
			color: #666;
			position: relative;

			&:not(:last-child)::after {
				content: '';
				position: absolute;
				right: 0;
				top: 50%;
				transform: translateY(-50%);
				width: 1px;
				height: 14px;
				background-color: #eee;
			}

			text {
				&.active {
					color: #f56c6c;
				}
			}

			.sort-arrow {
				margin-left: 4px;
				font-size: 12px;
			}
		}
	}

	.goods-container {
		padding: 10px;
	}

	.goods-list {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 10px;
		padding: 0 15px;

		&.list-view {
			display: block;

			.goods-item {
				display: flex;
				margin-bottom: 10px;
				background-color: #fff;
				border-radius: 8px;

				.goods-image {
					width: 120px;
					height: 120px;
					padding-top: 0;
					flex-shrink: 0;

					img {
						position: relative;
						height: 100%;
						object-fit: cover;
					}
				}

				.goods-info {
					flex: 1;
					padding: 10px;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.goods-title {
						margin-bottom: 0;
					}

					.goods-price-row {
						margin-top: auto;
					}
				}
			}
		}
	}

	.goods-item {
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
		position: relative;

		.goods-image {
			position: relative;
			padding-top: 100%;

			img {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				object-fit: cover;
			}

			.goods-tag {
				position: absolute;
				top: 8px;
				right: 8px;
				background-color: #f56c6c;
				color: #fff;
				padding: 2px 6px;
				border-radius: 4px;
				font-size: 12px;
			}
		}

		.goods-info {
			padding: 8px;

			.goods-title {
				font-size: 14px;
				color: #333;
				margin-bottom: 4px;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				overflow: hidden;
			}

			.goods-price-row {
				display: flex;
				align-items: baseline;

				.goods-price {
					color: #f56c6c;
					font-size: 16px;
					font-weight: bold;
				}

				.goods-unit {
					color: #999;
					font-size: 12px;
					margin-left: 2px;
				}
			}
		}
	}

	.search-history {
		background-color: #fff;
		padding: 15px;
		margin-top: 1px;

		.history-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15px;

			.history-title {
				font-size: 14px;
				color: #999;
			}
		}

		.history-tags {
			display: flex;
			flex-wrap: wrap;
			gap: 10px;

			.history-tag {
				padding: 6px 12px;
				background-color: #f5f5f5;
				border-radius: 4px;
				font-size: 12px;
				color: #666;
			}
		}
	}

	.column-center {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.img-null {
		width: 300rpx;
		height: 300rpx;
	}

	.search-loading {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40px 0;
		background-color: #fff;
		margin: 10px 15px;
		border-radius: 8px;

		text {
			margin-top: 10px;
			font-size: 14px;
			color: #666;
		}
	}
</style>